package org.jeecg.modules.controller.questions;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.modules.questions.entity.HistoryInfo;
import org.jeecg.common.modules.questions.entity.QuestionAll;
import org.jeecg.common.modules.questions.entity.QuestionHistory;
import org.jeecg.common.modules.questions.service.IHistoryInfoService;
import org.jeecg.common.modules.questions.service.IQuestionAllService;
import org.jeecg.common.modules.questions.service.IQuestionHistoryService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.UidUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 题库新
 * @Author: jeecg-boot
 * @Date: 2022-02-09
 * @Version: V1.0
 */
@Api(tags = "题库新")
@RestController
@RequestMapping("/api/v1/questionAllCopy")
@Slf4j
public class QuestionAllControllerCopye extends JeecgController<QuestionAll, IQuestionAllService> {
    @Autowired
    private IQuestionAllService questionAllService;
    @Autowired
    private IQuestionHistoryService questionHistoryService;
    @Autowired
    private IHistoryInfoService historyInfoService;

    /**
     * 获取默认模板ID
     *
     * @return
     */
    @AutoLog(value = "获取默认模板ID")
    @ApiOperation(value = "获取默认模板ID", notes = "获取默认模板ID")
    @PostMapping(value = "/getTemplateId")
    public Result<?> getTemplateId() {
        QuestionAll template = questionAllService.getOne(Wrappers.lambdaQuery(QuestionAll.class).eq(QuestionAll::getIsRelease,"1").last(" limit 1"));
        return Result.ok(template);
    }

    /**
     * 分页模板列表查询
     *
     * @param questionAll
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "题库新-模板分页列表查询")
    @ApiOperation(value = "题库新-分页列表查询", notes = "题库新-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(@RequestBody QuestionAll questionAll,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<QuestionAll> queryWrapper = QueryGenerator.initQueryWrapper(questionAll, req.getParameterMap());
        queryWrapper.eq("template_type", "模板");
        Page<QuestionAll> page = new Page<QuestionAll>(pageNo, pageSize);
        IPage<QuestionAll> pageList = questionAllService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 分页模板列表查询
     *
     * @param questionAll
     * @param req
     * @return
     */
    @AutoLog(value = "题库新-模板分页列表查询")
    @ApiOperation(value = "题库新-分页列表查询", notes = "题库新-分页列表查询")
    @PostMapping(value = "/questionList")
    public Result<?> queryquestionList(@RequestBody QuestionVO questionAll, HttpServletRequest req) {
        List<QuestionVO> questionVOS = new ArrayList<>();
        QuestionHistory questionHistory1 = questionHistoryService.getOne(Wrappers.lambdaQuery(QuestionHistory.class).eq(QuestionHistory::getOpenid,questionAll.getOpenid()).orderByDesc(QuestionHistory::getCreateTime).last(" limit 1"));
        questionAll.setTemplateId(questionHistory1.getTemplateId());
        List<QuestionAll> questionList = questionAllService.list(Wrappers.lambdaQuery(QuestionAll.class).eq(QuestionAll::getTemplateType, "问题").eq(QuestionAll::getTemplateId,questionAll.getTemplateId()).orderByAsc(QuestionAll::getQuestionNumber));
        for (QuestionAll question : questionList) {
            QuestionVO questionVO = new QuestionVO();
            BeanUtils.copyProperties(question,questionVO);
            List<QuestionAll> answerList = questionAllService.list(Wrappers.lambdaQuery(QuestionAll.class).eq(QuestionAll::getTemplateType, "答案").eq(QuestionAll::getTemplateId,questionAll.getTemplateId()).orderByAsc(QuestionAll::getQuestionNumber));
            if(!answerList.isEmpty()&&answerList!=null&&answerList.size()>0){
                List<AnswerVO> answerVOs = new ArrayList<>();
                AnswerVO answerVO1 = new AnswerVO();
                for (QuestionAll answerVO: answerList) {
                    BeanUtils.copyProperties(answerVO,answerVO1);
                    answerVOs.add(answerVO1);
                }
                questionVO.setAnswerList(answerVOs);
            }
            questionVOS.add(questionVO);
        }
        return Result.ok(questionVOS);
    }



    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "题库新-通过id删除")
    @ApiOperation(value = "题库新-通过id删除", notes = "题库新-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        questionAllService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "题库新-批量删除")
    @ApiOperation(value = "题库新-批量删除", notes = "题库新-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.questionAllService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "题库新-通过id查询")
    @ApiOperation(value = "题库新-通过id查询", notes = "题库新-通过id查询")
    @PostMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        QuestionAll questionAll = questionAllService.getById(id);
        if (questionAll == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(questionAll);
    }


    /**
     * 进入问卷调查
     *
     * @return
     */
    @AutoLog(value = "进入问卷调查")
    @ApiOperation(value = "进入问卷调查", notes = "进入问卷调查")
    @PostMapping(value = "/queryNextQuestion")
    public Result<?> queryNextQuestion(@RequestBody QuestionVO questionAll){
        QuestionHistory questionHistory = new QuestionHistory();
        QuestionVO questionVO = new QuestionVO();
        List<AnswerVO> answerVOS = new ArrayList<>();

        //第一次进来questionNumber 为空
        if(questionAll.getQuestionNumber() == null&&questionAll.getIntoQuestion()==null){
            String templateId = UidUtils.getUid32();
            questionHistory.setId(templateId);
            questionHistory.setTemplateId(questionAll.getTemplateId());
            questionHistory.setOpenid(questionAll.getOpenid());
            questionHistoryService.save(questionHistory);

            questionVO.setTemplateId(questionAll.getTemplateId());
            questionVO.setQuestionNumber("1");
            questionVO.setTitle("姓名");
            questionVO.setHistoryId(templateId);
            questionVO.setQuestionType("2");
            questionVO.setJumpQuestion(2);
            questionVO.setOpenid(questionAll.getOpenid());
            questionVO.setInfos(gethistoryInfos(templateId));
            return Result.ok(questionVO);
        }else if("1".equals(questionAll.getQuestionNumber()) && questionAll.getJumpQuestion() == 2&&questionAll.getIntoQuestion()==null){
            //保存上一题问题和答案
            saveHistoryInfo(questionAll);
            //保存上一题答案，获取下一题数据
            QuestionHistory history = questionHistoryService.getById(questionAll.getHistoryId());
            history.setName(questionAll.getAnswer());
            questionHistoryService.updateById(history);

            AnswerVO answerVO = new AnswerVO();
            answerVO.setQuestionNumber("A");
            answerVO.setJumpQuestion(3);
            questionVO.setAnswer("男");
            AnswerVO answerVO1 = new AnswerVO();
            answerVO1.setQuestionNumber("B");
            answerVO1.setJumpQuestion(3);
            answerVO1.setAnswer("女");
            answerVOS.add(answerVO);
            answerVOS.add(answerVO1);

            questionVO.setTemplateId(questionAll.getTemplateId());
            questionVO.setQuestionNumber("2");
            questionVO.setTitle("性别");
            questionVO.setQuestionType("1");
            questionVO.setHistoryId(questionAll.getHistoryId());
            questionVO.setJumpQuestion(3);
            questionVO.setOpenid(questionAll.getOpenid());
            questionVO.setInfos(gethistoryInfos(questionAll.getHistoryId()));
            questionVO.setAnswerList(answerVOS);
            return Result.ok(questionVO);
        } else if("2".equals(questionAll.getQuestionNumber()) && questionAll.getJumpQuestion() == 3&&questionAll.getIntoQuestion()==null){
            //保存上一题问题和答案
            saveHistoryInfo(questionAll);
            //保存上一题答案，获取下一题数据
            QuestionHistory history = questionHistoryService.getById(questionAll.getHistoryId());
            history.setSex(questionAll.getAnswer());
            questionHistoryService.updateById(history);
            questionVO.setTemplateId(questionAll.getTemplateId());
            questionVO.setQuestionNumber("3");
            questionVO.setTitle("年龄");
            questionVO.setQuestionType("2");
            questionVO.setHistoryId(questionAll.getHistoryId());
            questionVO.setJumpQuestion(4);
            questionVO.setOpenid(questionAll.getOpenid());
            questionVO.setInfos(gethistoryInfos(questionAll.getHistoryId()));
            return Result.ok(questionVO);
        } else if("3".equals(questionAll.getQuestionNumber()) && questionAll.getJumpQuestion() == 4&&questionAll.getIntoQuestion()==null){
            //保存上一题问题和答案
            saveHistoryInfo(questionAll);
            //保存上一题答案，获取下一题数据
            QuestionHistory history = questionHistoryService.getById(questionAll.getHistoryId());
            history.setAge(questionAll.getAnswer());
            questionHistoryService.updateById(history);
            questionVO.setTemplateId(questionAll.getTemplateId());
            questionVO.setQuestionNumber("3");
            questionVO.setTitle("手机号");
            questionVO.setQuestionType("1");
            questionVO.setHistoryId(questionAll.getHistoryId());
            questionVO.setJumpQuestion(4);
            questionVO.setOpenid(questionAll.getOpenid());
            questionVO.setInfos(gethistoryInfos(questionAll.getHistoryId()));
            return Result.ok(questionVO);
        } else if("4".equals(questionAll.getQuestionNumber()) && questionAll.getJumpQuestion() == 5&&questionAll.getIntoQuestion()==null){
            //保存上一题问题和答案
            saveHistoryInfo(questionAll);
            //保存上一题答案，获取下一题数据
            QuestionHistory history = questionHistoryService.getById(questionAll.getHistoryId());
            history.setPhone(questionAll.getAnswer());
            questionHistoryService.updateById(history);
            questionVO.setTemplateId(questionAll.getTemplateId());
            questionVO.setQuestionNumber("0");
            questionVO.setTitle("地址");
            questionVO.setQuestionType("1");
            questionVO.setHistoryId(questionAll.getHistoryId());
            questionVO.setJumpQuestion(1);
            questionVO.setOpenid(questionAll.getOpenid());
            questionVO.setIntoQuestion("0");
            questionVO.setInfos(gethistoryInfos(questionAll.getHistoryId()));
            return Result.ok(questionVO);
        }    else{
            if("0".equals(questionAll.getQuestionNumber()) && questionAll.getJumpQuestion() == 1&&questionAll.getIntoQuestion()!=null){
                //保存上一题答案，获取下一题数据
                QuestionHistory history = questionHistoryService.getById(questionAll.getHistoryId());
                history.setAddress(questionAll.getAnswer());
            }

            if(questionAll != null &&questionAll.getJumpQuestion()== null){
                QuestionVO questionVO1 = new QuestionVO();
                //保存上一题问题和答案
                questionAll.setQuestionNumber(Integer.valueOf(questionAll.getQuestionNumber()+4)+"");
                saveHistoryInfo(questionAll);
                return Result.ok(questionVO1);
            }else{
                questionAll.setQuestionNumber(Integer.valueOf(questionAll.getQuestionNumber()+4)+"");
            }

            //保存上一题问题和答案
            saveHistoryInfo(questionAll);
            questionAll.setQuestionNumber(Integer.valueOf(questionAll.getQuestionNumber())-4+"");
            //获取下一题
            return Result.ok(getNextQuestion(questionAll,questionAll.getHistoryId()));
        }
    }
    private void saveHistoryInfo(QuestionVO questionAll){
        HistoryInfo historyInfo = new HistoryInfo();
        HistoryInfo info = historyInfoService.getOne(Wrappers.lambdaQuery(HistoryInfo.class).eq(HistoryInfo::getHistoryId,questionAll.getHistoryId()).eq(HistoryInfo::getQuestionId,questionAll.getQuestionNumber()));
        if(info!=null){
            info.setAnswer(questionAll.getAnswer());
            historyInfoService.updateById(info);
        }else{
            historyInfo.setHistoryId(questionAll.getHistoryId());
            historyInfo.setNumber(questionAll.getJumpQuestion()+"");
            historyInfo.setQuestionId(questionAll.getQuestionNumber());
            historyInfo.setQuestion(questionAll.getTitle());
            historyInfo.setAnswer(questionAll.getAnswer());
            historyInfoService.save(historyInfo);
        }
    }

    private QuestionVO getNextQuestion(QuestionVO questionAll,String historyId){
        List<AnswerVO> answerList = new ArrayList<>();
        QuestionVO questionVO = new QuestionVO();
        //获取问题
        QuestionAll question = questionAllService.getOne(Wrappers.lambdaQuery(QuestionAll.class).eq(QuestionAll::getTemplateId,questionAll.getTemplateId()).eq(QuestionAll::getTemplateType,"问题")
        .eq(QuestionAll::getQuestionNumber,questionAll.getJumpQuestion()).last(" limit 1"));
        if(question == null){
            return questionVO;
        }
        BeanUtils.copyProperties(question, questionVO);
        List<QuestionAll> answers = questionAllService.list(Wrappers.lambdaQuery(QuestionAll.class).eq(QuestionAll::getTemplateId,questionAll.getTemplateId()).eq(QuestionAll::getTemplateType,"答案")
                .eq(QuestionAll::getParentId,questionAll.getJumpQuestion()));
        for (QuestionAll answer:answers) {
            AnswerVO answerVO = new AnswerVO();
            BeanUtils.copyProperties(answer,answerVO);
            answerVO.setAnswer(answer.getTitle());
            answerList.add(answerVO);
        }
        questionVO.setHistoryId(historyId);
        questionVO.setAnswerList(answerList);
        questionVO.setInfos(gethistoryInfos(historyId));
        questionVO.setIntoQuestion("0");
        questionVO.setOpenid(questionAll.getOpenid());
        return questionVO;
    }


    /**
     * 患者查询历史问卷
     *
     * @param questionHistory
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "历史主表-分页列表查询")
    @ApiOperation(value="历史主表-分页列表查询", notes="历史主表-分页列表查询")
    @PostMapping(value = "/historyList")
    public Result<?> queryhistoryList(@RequestBody QuestionHistory questionHistory,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<QuestionHistory> queryWrapper = QueryGenerator.initQueryWrapper(questionHistory, req.getParameterMap());
        queryWrapper.eq("openid",questionHistory.getOpenid());
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last(" limit 1");
        Page<QuestionHistory> page = new Page<QuestionHistory>(pageNo, pageSize);
        IPage<QuestionHistory> pageList = questionHistoryService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 患者查询历史问卷
     *
     * @return
     */
    @AutoLog(value = "历史主表-分页列表查询")
    @ApiOperation(value="历史主表-分页列表查询", notes="历史主表-分页列表查询")
    @PostMapping(value = "/historyDetails")
    public Result<?> queryhistoryDetails(@RequestBody QuestionHistory questionHistory) {
        QuestionHistory questionHistory1 = questionHistoryService.getOne(Wrappers.lambdaQuery(QuestionHistory.class).eq(QuestionHistory::getOpenid,questionHistory.getOpenid()).orderByAsc(QuestionHistory::getCreateTime).last(" limit 1"));
        return Result.ok(questionHistory1);
    }
    /**
     * 获取历史回答问卷
     *
     * @param
     * @return
     */
    @AutoLog(value = "历史回答问卷")
    @ApiOperation(value = "历史回答问卷", notes = "历史回答问卷")
    @PostMapping(value = "/history")
    public Result<?> getHistory(@RequestBody QuestionHistory questionHistory){
        String id = questionHistory.getId();
        HistoryInfoVO historyInfoVO = new HistoryInfoVO();
        List<QuestionVO> questionVOS = new ArrayList<>();
        QuestionVO questionVO = new QuestionVO();
        //查询历史详情
        QuestionHistory historty = questionHistoryService.getById(id);
        BeanUtils.copyProperties(historty,historyInfoVO);
        List<HistoryInfo> info = historyInfoService.list(Wrappers.lambdaQuery(HistoryInfo.class).eq(HistoryInfo::getHistoryId,id).orderByAsc(HistoryInfo::getQuestionId));
        historyInfoVO.setHistoryInfoList(info);
        return Result.ok(historyInfoVO);
    }
    private List<HistoryInfo> gethistoryInfos(String historyId){
        String id = historyId;
        //查询历史详情
        List<HistoryInfo> infos = historyInfoService.list(Wrappers.lambdaQuery(HistoryInfo.class).eq(HistoryInfo::getHistoryId,id).orderByAsc(HistoryInfo::getNumber));
        return infos;
    }
    /**
     *  编辑
     *
     * @param historyInfo
     * @return
     */
    @AutoLog(value = "历史子表-编辑")
    @ApiOperation(value="历史子表-编辑", notes="历史子表-编辑")
    @PostMapping(value = "/updateHistoryInfo")
    public Result<?> updateHistoryInfo(@RequestBody HistoryInfo historyInfo) {
        historyInfoService.updateById(historyInfo);
        return Result.ok("编辑成功!");
    }
    /**
     *  编辑
     *
     * @param
     * @return
     */
    @AutoLog(value = "历史子表-编辑")
    @ApiOperation(value="历史子表-编辑", notes="历史子表-编辑")
    @PostMapping(value = "/getAllQuestion")
    public List<HistoryInfo> getAllQuestion(@RequestBody QuestionHistory questionHistory){
        QuestionHistory questionHistory1 = questionHistoryService.getOne(Wrappers.lambdaQuery(QuestionHistory.class).eq(QuestionHistory::getOpenid, questionHistory.getOpenid()).isNotNull(QuestionHistory::getName).orderByDesc(QuestionHistory::getCreateTime).last(" limit 1"));
        if(questionHistory1 == null){
            return new ArrayList<>();
        }
        String id = questionHistory1.getId();
        //查询历史详情
        List<HistoryInfo> infos = historyInfoService.list(Wrappers.lambdaQuery(HistoryInfo.class).eq(HistoryInfo::getHistoryId,id).last( "  order by question_id+0 asc"));
        return infos;
    }
}
